package com.hjj.tij4.typeinfo;//: typeinfo/ClassInitialization.java

import java.util.*;

/**
 * <p>java中使用类而做的准备工作实际包含三个步骤</p>
 * <ul>
 *     <li>加载：这是由类加载器执行的。将查找字节码，并从这些字节码中创建一个Class对象</li>
 *     <li>链接：验证类中的字节码，为静态域分配存储空间</li>
 *     <li>初始化：如果该类具有父类，则对其初始化，执行静态初始化器和静态初始化块</li>
 * </ul>
 */
class Initable {
    static final int staticFinal = 47;
    static final int staticFinal2 =
            ClassInitialization.rand.nextInt(1000);

    static {
        System.out.println("Initializing Initable");
    }
}

class Initable2 {
    static int staticNonFinal = 147;

    static {
        System.out.println("Initializing Initable2");
    }
}

class Initable3 {
    static int staticNonFinal = 74;

    static {
        System.out.println("Initializing Initable3");
    }
}

public class ClassInitialization {
    public static Random rand = new Random(47);

    public static void main(String[] args) throws Exception {
        Class initable = Initable.class;
        System.out.println("After creating Initable ref");
        // Does not trigger initialization:
        System.out.println(Initable.staticFinal);
        // Does trigger initialization:
        System.out.println(Initable.staticFinal2);
        // Does trigger initialization:
        System.out.println(Initable2.staticNonFinal);
        Class initable3 = Class.forName("Initable3");
        System.out.println("After creating Initable3 ref");
        System.out.println(Initable3.staticNonFinal);
    }
} /* Output:
After creating Initable ref
47
Initializing Initable
258
Initializing Initable2
147
Initializing Initable3
After creating Initable3 ref
74
*///:~
